import React, {Component} from 'react';
import {
    Dimensions,
    Image,
    StyleSheet,
    View,
    TouchableOpacity,
    ScrollView,
    ListView,
    StatusBar,
    Alert
} from 'react-native';
const {width,height} = Dimensions.get('window');
import Swiper                     from 'react-native-swiper';
import MenuView                   from '../../views/MenuView';
import api                        from '../../utils/api';
import * as BaseAPI               from "../../utils/BaseAPI";
// import {NavigationActions}        from "react-navigation";
import StorageUtil                from '../../utils/StorageUtil';
import BannerDetail     from '../../screens/home/BannerDetailScreen';
import PersonalInfo from "../my/PersonalInfoScreen";

export default class HomeScreen extends Component {
    // static navigationOptions = {
    //     tabBarLabel: '首页',
    //     tabBarIcon: ({focused, tintColor}) => {
    //         if (focused) {
    //             return (
    //                 <Image style={styles.tabBarIcon} source={require('../../../images/tab/tab_home_selected.png')}/>
    //             );
    //         }
    //         return (
    //             <Image style={styles.tabBarIcon} source={require('../../../images/tab/tab_home_normal.png')}/>
    //         );
    //     },
    // };

    constructor(props) {
        super(props);
        this.state = {
            banners:[],
            welfares:[],
            noData:'',
            dataSource : new ListView.DataSource(
                { rowHasChanged: (r1, r2) => r1.uuid !== r2.uuid }),
        };
    }

    componentWillMount() {
        StorageUtil.get('token',(error,object)=>{
            if (!error && object != null)
            {
                // this.setState({token:object.token});

                this.getHomeData(object.token);
            }
        });
    }

    getHomeData(token){
        // this.setState({showProgress:true});

        console.log("数据首页"+ BaseAPI.GetHomeDataUrl+token);

        fetch(BaseAPI.GetHomeDataUrl+token, {
            method:'GET'
        }).then((res)=>res.json())
            .then((json)=>{

                console.log('首页哈哈哈哈'+ json + JSON.stringify(json));

                if (json.ret === 0){
                    // if (json.list.banner.length === 0){
                    //
                    // }else if (json.list.welfare.length === 0){
                    //
                    // }
                    this.setState({banners:json.list.banner});
                    this.setState({welfares:json.list.welfare});
                    console.log('树叶' + JSON.stringify(json.list.banner) );

                    this.setState({
                        dataSource:this.state.dataSource.cloneWithRows(json.list.welfare)
                    });

                } else {

                }

                // console.log('数据首页返回的'+ json + JSON.stringify(json));

                // console.log('短信收到'+ json + JSON.stringify(json));

                // // this.setState({showProgress:false});
                // if (json.ret === 0 ) {
                //     this.refs.toast.show('短信已发送,请注意查收');
                // }
                // else {
                //     this.refs.toast.show('短信获取失败,请过段时间重新获取');
                // }
            })
            .catch((e)=>{

                console.log('首页数据失败'+ e + JSON.stringify(e));

                this.setState({showProgress:false});
                // // 网络错误
                this.refs.toast.show('网络请求出错：' + e);
            })
    }

    // banner详情
    onPress(banner) {
        // this.props.navigation.navigate("BannerDetail",{bannerDetailUrl:banner.adurl})
        this.props.navigator.push({component:BannerDetail,params:{bannerDetailUrl:banner.adurl}})
    }

    onMenuSelected(item){
        if (item.title === '领取彩票') {
            this.props.navigation.navigate("ReceiveLottery")
        }else if(item.title === '领取荷豆'){
            this.props.navigation.navigate("ReceiveBeans")
        }else if(item.title === '玩转荷豆'){
            this.props.navigation.navigate("SkilledBeans")
        }else if(item.title === '荷豆兑奖'){
            this.props.navigation.navigate("BeansPrize")
        }
    }

    // 扫雷游戏
    goMineGame(){
        this.props.navigation.navigate("MineGame")
    }

    // 罗宾汉游戏
    goRobinHoodGame(){
        this.props.navigation.navigate("RobinHoodGame")
    }

    // 天天福利
    goWelfare(){
        this.props.navigation.navigate("Welfare")
    }

    renderFooterView(){
        return (
            <View style={{width: width, height:0.56*40}}/>
        )
    }

    goGameDetail(rowData){
        Alert.alert("游戏详情");
    }


    renderRow(rowData){

        console.log('数据Banner'+  rowData + JSON.stringify(rowData));

        return (
            <View style = {styles.cellViewStyle}>
                <TouchableOpacity activeOpacity={1} onPress={()=>{this.goGameDetail(rowData)}}>
                    <Image style={styles.gameImageStyle}
                           source={{url:BaseAPI.BasePhotoUrl+rowData.banner}}/>
                </TouchableOpacity>
            </View>
        )
    }

    renderHeaderView(){


        // console.log("数据首页"+ BaseAPI.GetHomeDataUrl+token);

        fetch(BaseAPI.GetHomeDataUrl+this.state.token, {
            method:'GET'
        }).then((res)=>res.json())
            .then((json)=>{

                console.log('sssss首页哈哈哈哈'+ json + JSON.stringify(json));

                if (json.ret === 0){
                    this.setState({banners:json.list.banner});
                    this.setState({welfares:json.list.welfare});
                    console.log('树叶' + JSON.stringify(json.list.banner) );

                    this.setState({
                        dataSource:this.state.dataSource.cloneWithRows(json.list.welfare)
                    });

                } else {

                }

                // console.log('数据首页返回的'+ json + JSON.stringify(json));

                // console.log('短信收到'+ json + JSON.stringify(json));

                // // this.setState({showProgress:false});
                // if (json.ret === 0 ) {
                //     this.refs.toast.show('短信已发送,请注意查收');
                // }
                // else {
                //     this.refs.toast.show('短信获取失败,请过段时间重新获取');
                // }
            })
            .catch((e)=>{

                console.log('首页数据失败'+ e + JSON.stringify(e));

                this.setState({showProgress:false});
                // // 网络错误
                this.refs.toast.show('网络请求出错：' + e);
            })


        console.log('点击数据'+ this.state.banners + JSON.stringify(this.state.banners));

        var bannerList = [
            'http://192.168.6.203:8990//client/upload/banner/banner_123456.png',
            'http://192.168.6.203:8990//client/upload/banner/banner_123456.png',
            'http://192.168.6.203:8990//client/upload/banner/banner_123456.png'
        ];

        return (

            <View>
                <Swiper
                    horizontal={true}
                    height={200}
                    loop={true}
                    autoplay={true}
                    paginationStyle={{bottom:10}}
                    dot={<View style={styles.customDot} />}
                    activeDot={<View style={styles.customActiveDot} />}
                >
                    {
                        bannerList.map((banner,i) => {
                            return (
                                <TouchableOpacity key={i} activeOpacity={1}
                                                  onPress={() => this.onPress(banner)}>
                                    <Image
                                        style={styles.bannerImage}
                                        // source={{uri:banner}}
                                        source={{uri:BaseAPI.BasePhotoUrl+banner.banner}}
                                    />
                                </TouchableOpacity>
                            )
                        })
                    }
                </Swiper>

                <View style={styles.menuViewStyle}>
                    <Image style={styles.menuTitleStyle}
                           source={require('../../../images/home/icon-jingxvan.png')}/>
                </View>
                <View style={{flex:1}} />

            </View>



        )
    }

    // renderHeaderView(){
    //     var banners = this.state.banners;
    //     return (
    //         <Swiper
    //             horizontal={true}
    //             height={200}
    //             loop={true}
    //             autoplay={true}
    //             paginationStyle={{bottom:10}}
    //             dot={<View style={styles.customDot} />}
    //             activeDot={<View style={styles.customActiveDot} />}
    //         >
    //             {
    //                 banners.map((banner,i) => {
    //                     return (
    //                         <TouchableOpacity key={i} activeOpacity={1}
    //                                           onPress={() => this.onPress(banner)}>
    //                             <Image
    //                                 style={styles.bannerImage}
    //                                 source={{uri:BaseAPI.BasePhotoUrl+banner.banner}}
    //                             />
    //                         </TouchableOpacity>
    //                     )
    //                 })
    //             }
    //         </Swiper>
    //     )
    // }


    render() {
        var bannerList = [
            'http://img1.3lian.com/2015/w7/98/d/22.jpg',
            'http://img1.3lian.com/2015/w7/98/d/22.jpg',
            'http://img1.3lian.com/2015/w7/98/d/22.jpg'
        ];

        var bannerStr = this.state.welfares[0];

        console.log("访问中--"+ JSON.stringify(this.state.welfares[0]));

        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="#394f8b"
                    barStyle="light-content"
                />

                <ScrollView>

                    <Swiper
                        horizontal={true}
                        height={200}
                        loop={true}
                        autoplay={true}
                        paginationStyle={{bottom:10}}
                        dot={<View style={styles.customDot} />}
                        activeDot={<View style={styles.customActiveDot} />}
                    >
                        {
                            this.state.banners.map((banner,i) => {
                                return (
                                    <TouchableOpacity key={i} activeOpacity={1}
                                                      onPress={() => this.onPress(banner)}>
                                        <Image
                                            style={styles.bannerImage}
                                            // source={{uri:banner}}
                                            source={{uri:BaseAPI.BasePhotoUrl+banner.banner}}
                                        />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </Swiper>

                    {/*<MenuView menuInfos={api.menuInfo}  props={this.props} onMenuSelected={(this.onMenuSelected)} />*/}

                    {/*<ListView*/}
                    {/*showsVerticalScrollIndicator={false}*/}
                    {/*dataSource={this.state.dataSource}*/}
                    {/*renderRow={this.renderRow.bind(this)}*/}
                    {/*renderHeader={this.renderHeaderView}*/}
                    {/*renderFooter={this.renderFooterView}*/}
                    {/*/>*/}



                    <View style={{width: width, height:0.56*10}}/>

                    <View style={styles.menuViewStyle}>
                        <Image
                            style={styles.menuTitleStyle}
                            source={require('../../../images/home/icon-jingxvan.png')}
                        />
                    </View>

                    <View style={styles.gameViewStyle}>
                        <TouchableOpacity  activeOpacity={1}
                                           onPress={() => this.goMineGame()}>
                            {
                                this.state.welfares.map((banner,i) => {
                                    return (
                                        <TouchableOpacity key={i} activeOpacity={1}
                                                          onPress={() => this.onPress(banner)}>
                                            <Image
                                                style={styles.gameImageStyle}
                                                // source={{uri:banner}}
                                                source={{uri:BaseAPI.BasePhotoUrl+banner.banner}}
                                            />
                                        </TouchableOpacity>
                                    )
                                })
                            }
                            {/*<Image*/}
                            {/*style={styles.gameImageStyle}*/}
                            {/*source={{uri:this.state.welfares[0].banner}}*/}
                            {/*// source={require('../../../images/home/home_game.png')}*/}
                            {/*/>*/}
                        </TouchableOpacity>

                        {/*<View style={{width: width, height:0.56*10}}/>*/}
                        {/*<TouchableOpacity  activeOpacity={1}*/}
                        {/*onPress={() => this.goRobinHoodGame()}>*/}
                        {/*<Image*/}
                        {/*style={styles.gameImageStyle}*/}
                        {/*source={require('../../../images/home/home_game.png')}*/}
                        {/*/>*/}
                        {/*</TouchableOpacity>*/}

                    </View>

                    {/*<View style={styles.welfareMenuViewStyle}>*/}
                    {/*<Image*/}
                    {/*style={styles.welfareTitleStyle}*/}
                    {/*source={require('../../../images/home/icon-tiantian.png')}*/}
                    {/*/>*/}
                    {/*</View>*/}

                    {/*<View style={styles.welfareViewStyle}>*/}
                    {/*<TouchableOpacity  activeOpacity={1}*/}
                    {/*onPress={() => this.goWelfare()}>*/}
                    {/*<Image*/}
                    {/*style={styles.welfareImageStyle}*/}
                    {/*source={require('../../../images/home/home_welfare.png')}*/}
                    {/*/>*/}
                    {/*</TouchableOpacity>*/}
                    {/*</View>*/}

                </ScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    tabBarIcon: {
        width: 24,
        height: 24,
    },
    // TODO: banner setting
    customDot: {
        backgroundColor: '#ccc',
        height:6,
        width: 6,
        marginLeft: 2,
        marginRight: 2,
        marginTop:200,
        borderRadius:3,
    },
    customActiveDot: {
        backgroundColor:'white',
        height: 6,
        width: 6,
        marginLeft: 2,
        marginRight: 2,
        marginTop:200,
        borderRadius: 3,
    },
    bannerImage: {
        height:200,
        width:width,
    },
    menuViewStyle:{
        // marginTop:20,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
        height:0.56*86,
        // marginBottom:2,
        marginTop:5
    },
    menuTitleStyle:{
        height:0.56*37,
        width:0.56*274
    },
    welfareMenuViewStyle:{
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
        height:0.56*86
    },
    welfareTitleStyle:{
        height:0.56*37,
        width:0.56*345
    },
    gameViewStyle:{
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
        height:0.56*(148+10),
        flexDirection:'column',
    },
    gameImageStyle:{
        height:0.56*148,
        width:0.56*750,
    },
    welfareViewStyle:{
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
        // height:0.56*750
    },
    welfareImageStyle:{
        height:0.56*300,
        width:0.56*750
    }
});
